﻿//  --------------------------------
//  Copyright (c) Shawn Duggan. All rights reserved.
//  This source code is made available under the terms of the Microsoft Public License (Ms-PL)
//  http://www.opensource.org/licenses/ms-pl.html
//  ---------------------------------
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Windows.Documents;

namespace BlueTango.WPFControls
{
    public class StringToXamlConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                var flowDocument = new FlowDocument();
                
                var xaml = value.ToString();
                string valuestring = value.ToString();
                var text = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);

               

                using (var stream = new MemoryStream((new UTF8Encoding()).GetBytes(xaml)))
                {

                    if (valuestring.Contains("<") && valuestring.Contains(">"))
                    {
                        text.Load(stream, DataFormats.Xaml);
                    }
                    else
                    {
                        text.Load(stream, DataFormats.Text);
                    }
                  
                       
                   
                   
                       


               



                      
                   




                }

                return flowDocument;
            }
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                var flowDocument = (FlowDocument) value;
                var range = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);
                string xaml;

                using (var stream = new MemoryStream())
                {
                    range.Save(stream, TextDataFormat.Xaml.ToString());
                    stream.Seek(0, SeekOrigin.Begin);
                    using (var reader = new StreamReader(stream))
                    {
                        xaml = reader.ReadToEnd();
                    }
                }

                return xaml;
            }
            return value;
        }
    }
}